package com.bsj.travel.util.ip;

import cn.hutool.core.net.NetUtil;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author : zhuojie.c
 * @version V1.0
 * @Description: TODO
 * @date Date : 2025/1/15 15:40
 */
public class GetEth0IpUtil {

    private static final String TARGET_INTERFACE_NAME = "eth0";

    /**
     * 优先获取eth0-ip地址
     * 不存在，则获取本机其他地址
     * @return
     */
    public static String getHostAddress() {
        InetAddress inetAddress = getInetAddressByName();
        if (inetAddress != null) {
            return inetAddress.getHostAddress();
        } else {
            return GetEth0IpUtil.getHostAddress();
        }
    }

    private static InetAddress getInetAddressByName() {
        try {
            NetworkInterface networkInterface = NetworkInterface.getByName(GetEth0IpUtil.TARGET_INTERFACE_NAME);
            if (networkInterface == null || !networkInterface.isUp()) {
                // Interface not found or down
                return null;
            }

            // Iterate through all addresses of the specified network interface.
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                if (addr != null && !addr.isLoopbackAddress() && !addr.isLinkLocalAddress()) {
                    // Return the first non-loopback, non-link-local IPv4 address.
                    return addr;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        // No suitable address was found.
        return null;
    }

}
